package com.lemon.springboot.service.impl;

import com.lemon.springboot.dao.ICpuDao;
import com.lemon.springboot.entity.CpuVo;
import com.lemon.springboot.service.ICpuPageService;
import com.lemon.springboot.utils.DateUtil;
import com.lemon.springboot.utils.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author liuli
 * @Date 2020/12/20 12:20
 */
@Service
public class CpuPageServicImpl implements ICpuPageService {

    @Autowired
    ICpuDao cpuDao;

    @Override
    public Map<String, Object> findCpuDataByDate(Date startTime, Date endTime, String token, int maxDataCount) {
        Map<String, Object> result =  new HashMap<>();
        List<CpuVo> cpuDataList = cpuDao.findCpuByDate(startTime, endTime, token);
        List<String> field = Arrays.asList(new String[maxDataCount]);
        List<String> data = null;
        for (int i = 0; i < maxDataCount; i = i+2) {
            if (i == 0) {
                field.set(i, DateUtil.dateFormat(new Date(startTime.getTime() + i * DateUtil._30SEC), DateUtil.parent));
            }else {
                field.set(i, DateUtil.dateFormat(new Date(startTime.getTime() + i * DateUtil._30SEC), "HH:mm"));
            }
            result.put("fields", field);
        }
        if (cpuDataList != null && cpuDataList.size() > 0) {
            data = Arrays.asList(new String[maxDataCount]);
            for (CpuVo cpuVo : cpuDataList) {
                long time = cpuVo.getDate().getTime();
                int index = ((int) ((time - startTime.getTime()) / DateUtil._30SEC));
                data.set(index, NumberUtil.floatFormat(((double) cpuVo.getCpuUsage()) / 100, "0.00"));
            }
            result.put("data", data);
            result.put("model",cpuDataList.get(0).getCpuModel() + " CPU使用率(%)");
        }
        return result;
    }
}
